package com.whosly.foundationdb.study.config.jetty;

import com.whosly.foundationdb.study.config.jetty.handler.WebErrorWebExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;

import java.util.Collections;
import java.util.List;

/**
 *
 */
@Configuration
public class WebFluxConfiguration {

	@Primary
	@Bean
	public ErrorWebExceptionHandler errorWebExceptionHandler(WebFluxServerResponseWriter webFluxServerResponseWriter,
															 @Value("${nasoc.error.page.url:404}") String errorPageUrl) {
		WebErrorWebExceptionHandler errorWebExceptionHandler = new WebErrorWebExceptionHandler();
		errorWebExceptionHandler.setWebFluxServerResponseWriter(webFluxServerResponseWriter);
		errorWebExceptionHandler.setErrorPageUrl(errorPageUrl);
		return errorWebExceptionHandler;
	}

	@Bean
	public WebFluxServerResponseWriter webFluxServerResponseWriter(ObjectProvider<List<ViewResolver>> viewResolversProvider,
																   ServerCodecConfigurer serverCodecConfigurer) {
		WebFluxServerResponseWriter webFluxServerResponseWriter = new WebFluxServerResponseWriter();
		webFluxServerResponseWriter.setMessageReaders(serverCodecConfigurer.getReaders());
		webFluxServerResponseWriter.setMessageWriters(serverCodecConfigurer.getWriters());
		webFluxServerResponseWriter.setViewResolvers(viewResolversProvider.getIfAvailable(Collections::emptyList));
		return webFluxServerResponseWriter;
	}

}
